package com.ning.parking.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.ning.parking.domain.VO.BillingResult;
import com.scsonic.common.enums.parking.ParkingCarTypeEnum;
import com.scsonic.common.enums.trade.PayStatusEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Date;

@Service
public class ParkingFeeCalculator {

    // 使用字符串初始化保证精度
    private static final BigDecimal INITIAL_HOUR_RATE = new BigDecimal("5.00");   // 首小时费用
    private static final BigDecimal HALF_HOUR_RATE = new BigDecimal("1.25");     // 后续每半小时费用
    private static final int FREE_MINUTES = 15;                                  // 免费时长（分钟）

    public BillingResult tempBilling(Date entry, Date exit) {
        return tempBilling(entry,exit,BigDecimal.ZERO);
    }
    /**
     * 临停计费
     * @param entry 入场时间
     * @param exit 离场时间
     * @return
     */
    public BillingResult tempBilling(Date entry, Date exit, BigDecimal discountAmount) {

        LocalDateTime entryTime = LocalDateTime.ofInstant(entry.toInstant(), ZoneId.systemDefault());
        LocalDateTime exitTime = LocalDateTime.ofInstant(exit.toInstant(), ZoneId.systemDefault());

        // 时间有效性校验
        if (exitTime.isBefore(entryTime)) {
            throw new IllegalArgumentException("Exit time cannot be earlier than entry time");
        }
        BillingResult billingResult = new BillingResult();
        Duration duration = Duration.between(entryTime, exitTime);
        long totalMinutes = duration.toMinutes();
        // 免费时段处理
        if (totalMinutes <= FREE_MINUTES) {
            BigDecimal totalAmount = BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
            return billingResult;
        }
        // 计算基础费用（首小时）
        BigDecimal fee = INITIAL_HOUR_RATE;
        long remainingMinutes = totalMinutes - 60;

        if (remainingMinutes > 0) {
            // 计算后续费用（按半小时向上取整）
            BigDecimal halfHours = BigDecimal.valueOf(remainingMinutes)
                    .divide(BigDecimal.valueOf(30), 0, RoundingMode.CEILING);
            fee = fee.add(halfHours.multiply(HALF_HOUR_RATE));
        }
        // 金额保留两位小数
        BigDecimal totalAmount = fee;
        //总金额-优惠金额
        BigDecimal payableAmount = totalAmount.subtract(discountAmount);
        billingResult.setDiscountAmount(discountAmount);
        billingResult.setPayableAmount(payableAmount);
        billingResult.setTotalAmount(totalAmount);
        if (payableAmount.doubleValue() > 0) {
            billingResult.setPayStatus(PayStatusEnum.UN_PAY);
        }
        return billingResult;
    }
}
